Ext.namespace('VAS');

Ext.ux.DynamicGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
	
	page :  true,
	
	pageSize : 20,
	gridFilters:[],
	toolCount : 7,
	toolIndex : 0,
	
	initComponent  : function() {
		
		var _this = this;
		
		_storeId=Math.random();
//		var storeid=_this.storeId != undefined ?_this.storeId:Global.STD_GRID_STORE.id;
		var store = new Ext.data.Store({
			id     : typeof(_this.storeId) != 'undefined' ?_this.storeId:_storeId,
			url    : _this.storeUrl,
			reader : new Ext.data.JsonReader(),
			baseParams : {
				gridPanelId :_this.id,
				start       : 0,
				limit       : this.pageSize

			}
		});

    
    // create filters plugin
    _this.filters = new Ext.ux.grid.GridFilters( {
        local: true,
        filters: []
    });
    
		
		_this.detailWin = {};

		var config = {
			viewConfig      : {
				forceFit    : true
			},
			enableColLock   : false,
			loadMask        : true,
			border          : false,
			stripeRows      : true,
			columns         : [],
			tbar            : []
			, store: store
			,plugins:_this.filters

		};
		
		if (_this.page) {
			Ext.apply(config,{
				bbar : new Ext.PagingToolbar({
					pageSize     : this.pageSize,
					store        : store,
					displayInfo  : true,
					plugins: [
					    new Ext.ux.plugins.PageComboResizer({pageSizes: [5, 10, 15, 20, 30, 50],pageSize:this.pageSize})
					],
					displayMsg   : '第 {0} - {1} 条,共 {2}条',
					emptyMsg     : "没有数据",
					beforePageText : '第',
					afterPageText  : '页,共{0}页',
					firstText 	   : '首页',
					prevText 	   : '上一页',
					nextText	   : '下一页',
					lastText	   : '尾页',
					refreshText	   : '刷新'
				})
			});
		}
		this.on('cellclick',function(grid, rowIndex, columnIndex, e){
		if(typeof(_this.popUp)==='undefined'||_this.popUp===null){//只有在portal的grid才可有cellclick事件.
				
		var s=grid.getStore();
        var record=s.getAt(rowIndex);
        var cell=grid.getColumnModel().getColumnAt(columnIndex);         
        if (cell.img !== 'undefined'
							&& typeof(cell.img) === 'boolean') {
//								Ext.getBody().mask("Loading...","x-mask-loading");
//								var win=new VAS.CommQueryGridWin({popUp:{grid:grid,columnIndex:columnIndex,record:record,fromForm:false}});
//								win.show();
//						Ext.getBody().unmask();
					}
			}else{
				var s=grid.getStore();
                 var record=s.getAt(rowIndex);
				 var form=Ext.getCmp('commQueryWin_formPanel');
				 if(typeof(form) != 'undefined'){
		         	form.loadForm(record);
				 }
			}
		});
		
	
		Ext.apply(this, config);
		Ext.apply(this.initialConfig, config);
		Ext.ux.DynamicGridPanel.superclass.initComponent.apply(this, arguments);
	}

	,onRender : function(ct, position) {
		var _this = this;
		this.colModel.defaultSortable = true;
		Ext.ux.DynamicGridPanel.superclass.onRender.call(this, ct, position);
		var _panelId = this.id;
		
		var _params={}
		if(typeof(this.gridPanelParams)!=='undefined'&&typeof(this.gridPanelParams)==='object'){
			_params=this.gridPanelParams;
		    for(var prop in _params){
		    	if(typeof(_params[prop])!=='undefined'&&typeof(_params[prop])==='object'){
		    		_params[prop] = Ext.encode(_params[prop]);
		    	}
		    }
			_params.start=0;
			_params.limit=10;
			_params.gridPanelId=_panelId;			
			Ext.apply(this.store,{baseParams:_params});
		}

		
		this.store.load();
		var _data = SyncAjax(this.gridUrl, {
			gridPanelId : _panelId
		});

		_this.callback(_data);

	},

	callback : function(_data) {
		var _this = this;
		
		//设置列表的列信息
		this.setColumnModel(_data);
		if(withAdvancedSearch != 'undefined'){
			_data.withAdvancedSearch = withAdvancedSearch;
		}else{
			_data.withAdvancedSearch = true;	//值为false时，屏蔽掉高级搜索
		}
		_this.tb    =  this.getTopToolbar();

		if( _data.withAdvancedSearch == true ){
			//添加高级搜索框和按钮
			_this.tb.add(this.getAdvancedSearchComboBox());
			if(advancedSearchManageRightFlag == true){
				_this.tb.add('-');
				_this.tb.add(_this.getSearchButton());
			}
		}
		
		var _tbar =  _data.tbar;
		if (typeof(_tbar) === 'object' ) {
			var _tbLength = _tbar.length;
			_this.tb.add('->');
			for (var i = _this.toolIndex ;i <  _tbLength; i++){
				if (typeof(_tbar[i]) === 'object') {
					//_this.tb.add('->');
					_this.tb.add('-');
					_this.tb.add(_tbar[i]);
				}
				if( _tbLength>_this.toolCount && i>= _this.toolCount-1){
					//_this.tb.add('->');
					_this.tb.add('-');
					_this.tb.add(_this.getSlideButton(_data));
					_this.tb.add('-');
					break;
				}
			}
			/*
for (var i = _tbLength - 1; i > -1; i--) {
				if (typeof(_tbar[i]) === 'object') {
					_this.tb.add('->');
					_this.tb.add('-');
					_this.tb.add(_tbar[i]);
				}
				if(_tbLength - i >= this.toolCount && _tbLength>this.toolCount){
					_this.tb.add('->')
					_this.tb.add(_this.getSlideButton(_data));
					return;
				}
			}
*/
			Ext.apply(_this, {
				tbar : _this.tb
			});
		}		

		var _lisenters = _data.lisenters;

		Ext.each(_lisenters, function(lisenter) {
			if(lisenter.actionType==='rowdblclick'){
			_this.addListener("rowdblclick", function(_this, rowIndex, e) {
					if (typeof(_this.popUp) != 'undefined'
							&& typeof(_this.popUp) === 'object') {// dbclick后，把选中的record记录返回给Form表单
						if (_this.popUp.fromForm) {// 点了form的选择后弹出的window;
							var record = _this.getStore().getAt(rowIndex);
							_this.popUp.compositeSelect
									.setFilePathValue(record);
							var win = Ext.getCmp(_this.popUp.id);
							win.close();
						}
					} else {
						Ext.each(_tbar, function($tbar) {
							if (typeof(_tbar) != 'undefined'
									&& _tbar.length > 0) {// GRid如果不是弹出窗口。
								if ($tbar.actionType === Global.ACTION_TYPE_EDIT) {// dbclick后，弹出详情窗口。
									var editBar = _this.tb.find('actionType',
											Global.ACTION_TYPE_EDIT);
									editBar[0].editForm($tbar.action, $tbar.id,
											_this, Global.ACTION_TYPE_EDIT);
								}
							}
						})
					}

				})}
			else if(lisenter.actionType==='cellEditor'){//加入行编辑url
				var cellEditorUrl=lisenter.action;
				Ext.apply(_this,{cellEditorUrl:cellEditorUrl})
				
			}
	   });

	},
	
	
	setColumnModel : function(_data){
		var _this = this;
		
		if (typeof(_data.columns) === 'object') {
			var columns = [];
		
			if (this.rowNumberer) {
				columns.push(new Ext.grid.RowNumberer());
			}
			if (this.checkboxSelModel) {
				columns.push(new Ext.grid.CheckboxSelectionModel({
						defaults : {
							sortable : true								
						}
					})
				);
			}

			Ext.each(_data.columns, function(column) {
				
				if(typeof(column.img)!=='undefined'&&typeof(column.img)==='boolean'){
				   column.renderer=_this.onEntryStatus.createDelegate(_this);
				}
				//add the function which supprot regular expression;
				
				if(typeof(column.editor)!='undefined'&&typeof(column.editor.regexpr)!='undefined'){
					eval('column.editor.regex=/'+column.editor.regexpr+'/');		
	                 
					var regexText=typeof(column.editor.regexprText)!='undefined'?column.editor.regexprText:"";
					eval('column.editor.regexText="'+regexText+'"');
				}
				columns.push(column);
			});
			this.getColumnModel().setConfig(columns);
		}
		this.el.unmask();
	},
	
	getAdvancedSearchComboBox : function(){
		var _this = this;
		var advancedSearchComboBox =  new Ext.form.ComboBox({
			store   : new Ext.data.Store({
				proxy     : new Ext.data.HttpProxy({url:'admin/view/cfg!getViewPanelFilterByGridPanelId.action?gridPanelId='+_this.id+'&entryMenuId='+_this.menuid}),
				reader    : new Ext.data.JsonReader(
					{}, 
					[
						{name : 'id'},
						{name : 'name'},
						{name: 'viewpanelid'},
						{name: 'tips'},
						{name: 'filter'}
					]
				)
			}),
	        fieldLabel    : '高级搜索',
			mode          : 'remote',
			width         : 120,
			selectOnFocus : true, 
			forceSelection : true,
			typeAhead	  : true, 
			triggerAction : 'all',
			valueField    : 'filter',
			displayField  : 'name',
			emptyText	  : '高级搜索',
			listeners :{
	       		'select' : function(combo, record, index) {
					var _postData = record.data.filter;
					var limitTemp = _this.store.baseParams.limit;
					//初始化baseParams
					_this.store.baseParams = {
							gridPanelId :_this.id,
							start       : 0,
							limit       : limitTemp
					}
					//把查询条件赋给baseParams，供翻页时用
					Ext.apply(_this.store.baseParams,_postData)
					_this.store.load({
						params:  _postData
					});
	       		}
			}
		});
		return advancedSearchComboBox;
	},
	getSlideButton : function(_data){
		var _this = this;
		var menuItem = [];
		var _tbar =  _data.tbar;
		var _tbLength = _tbar.length;
		for(var i=_this.toolCount;i<_tbLength;i++){
			menuItem.push(_tbar[i]);
		}
		var slideButton = new Ext.SplitButton({
			text: '更多',
			icon: 'lib/ext-3.2.1/resources/images/default/layout/expand.gif',
			arrowAlign:'right',
			iconAlign : 'right',
			menu: {
				xtype :'menu',
				showSeparator :false,
				cls:'x-tab-panel-header',
				width : 88,
				items : {
					xtype: 'buttongroup',
					frame : false,
					border : false,
                    columns: 1,
					width: '100%',
                    defaults: {
                        xtype: 'button',
						scale: 'small',
						width: '99%',
                        iconAlign: 'left',
						anchor:'95%'
                    },
					items : menuItem
				}
			}
		});
		return slideButton;
	},
	getSearchButton : function(){
		var _this = this;
		var searchButton = new Ext.Button({
			text	: '高级搜索设置',
			icon    : 'lib/vas/img/search.png',
			handler : function() {
				
	 	   		Ext.Ajax.request({
					url    : 'http/gridFormWindow.json',
					method : "POST",
					params : {},			   
					success: function(response) {
						//检查session是否过期
						checkTimeOut(response);
						var responseObj = Ext.util.JSON.decode(response.responseText);
						if (responseObj.success) {
							if( typeof(responseObj.wins[0].fieldSetUrl) == 'string'){
								Ext.Ajax.request({
									url    : responseObj.wins[0].fieldSetUrl,
									method : "POST",
									params :{gridPanelId:_this.id, entryMenuId:_this.menuid},					   
									success: function(response) {
										//检查session是否过期
										checkTimeOut(response);
										var responseObj2 = Ext.util.JSON.decode(response.responseText);
										if (responseObj2.success) {
											var win = new VAS.AdvancedSearchWindow({
												modal: true,
												width: 670,
												wins : responseObj.wins[0],
												fieldSet : responseObj2.items,
												gridPanelId : _this.id,
												menuid : _this.menuid,
												advancedSearchComboBox : _this.getAdvancedSearchComboBox()
											});
											win.show();	
										} else {
											alertFailure(responseObj);
										}
									}, failure: function(response) {
										Ext.Msg.alert('提示','服务器异常！');
									}
						   		}) 
								
							}
						} else {
							alertFailure(responseObj);
						}
					}, failure: function(response) {
						Ext.Msg.alert('提示','服务器异常！');
					}
		    	});
    		}
		});
		return searchButton;
	},
	
	reload : function($params) {
		this.store.reload({
			params : $params
		});
	}

	,onEntryStatus: function(value,p,record){
     
       var img="<img src='"+value+"' '>";  
            p.attr='ext:qtip="'+img+'" style="background-image:url('+value+') !important;  background-repeat: no-repeat;cursor: pointer;"';
      
	}
	//override getView方法。给Ext.grid.GridView中文参数。
	 ,getView : function(){
        if(!this.view){
        	Ext.apply(this.viewConfig,{
            	sortAscText : '升序排列',
            	sortDescText : '降序排列',
            	columnsText : '列'
            });
            this.view = new Ext.grid.GridView(this.viewConfig);
        }
        return this.view;
    }
});
Ext.reg('dynamicGridPanel',Ext.ux.DynamicGridPanel);
